<template>
    <div class="content-wrapper-view">
		<div class="content-wrapper-body"><!-- 开始 -->

        <div class="filter-wrapper">
            <el-form ref="filterForm" :model="listQuery" :inline="true">
                <el-form-item prop="name" size="medium">
                    <el-input v-model="listQuery.name" placeholder="名称"></el-input>
                </el-form-item>

                <el-form-item prop="orderBy" size="medium">
                    <el-select v-model="listQuery.orderBy" placeholder="排序" style="width: 120px">
                        <el-option
                                v-for="item in sortOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-button type="primary" size="medium" icon="el-icon-search" @click="handleFilter">搜索</el-button>
                <el-button type="primary" size="medium" icon="el-icon-mars-reset" @click="handleResetFilter">重置</el-button>
                <el-button type="primary" size="medium" icon="el-icon-upload" @click="handleCreate">上传图片</el-button>
                <el-button type="danger" size="medium" icon="el-icon-delete" @click="handleBatchDelete">批量删除</el-button>
            </el-form>

        </div>

        <el-table
                :data="list"
                border fit
                highlight-current-row
                v-loading="listLoading"
                element-loading-text="给我一点时间"
                @selection-change="handleSelectionChange">

            <el-table-column
                    type="selection"
                    width="55" align="center">
            </el-table-column>
            <el-table-column type="index" width="55" align="center"></el-table-column>


            <el-table-column label="图片预览" align="center">
                <template slot-scope="scope">
                    <img v-if="scope.row.url" :src="scope.row.url" alt="" style="width: 100px;">
                </template>
            </el-table-column>

            <el-table-column label="图文素材图片URL" min-width="400px" align="center">
                <template slot-scope="scope"> {{scope.row.url}} </template>
            </el-table-column>

            <el-table-column label="备注" min-width="200px" align="center">
                <template slot-scope="scope"> {{scope.row.remarks}} </template>
            </el-table-column>

            <el-table-column label="创建时间" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.ctime | parseTime('{y}-{m}-{d} {h}:{i}')}} </template>
            </el-table-column>

            <el-table-column label="最后修改时间" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.utime | parseTime('{y}-{m}-{d} {h}:{i}')}} </template>
            </el-table-column>

            <el-table-column label="操作" width="180px" align="center">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" icon="edit" @click="handleUpdate(scope.row)">编辑</el-button>

                    <el-button size="small" type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="listQuery.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="listQuery.rows"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" @close="handleDialogClose">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="备注" prop="title">
                    <el-input v-model="form.remarks" style="width: 400px;"></el-input>
                </el-form-item>

                <el-form-item label="内容" style="width: 520px;" v-if="dialogStatus != 'update'">
                    <file-upload
                            class="select-file-bto lh-38"
                            :post-action="uploadAction"
                            :extensions="extensions"
                            :accept="accept"
                            :multiple="true"
                            :size="size || 0"
                            :thread="thread < 1 ? 1 : (thread > 5 ? 5 : thread)"
                            :headers="headers"
                            :drop="true"
                            :drop-directory="true"
                            v-model="files"
                            @input-filter="inputFilter"
                            @input-file="inputFile"
                            ref="upload">
                        选择文件
                    </file-upload>
                </el-form-item>

                <el-row :gutter="20" v-if="files.length > 0 && dialogStatus != 'update'">
                    <el-col :span="10">
                        <el-form-item>
                            <div class="img-preview">
                                <div class="img-box">
                                    <img v-if="files" :src="files[0].thumb" width="40" height="auto" />
                                </div>
                                <div class="progress">
                                    <el-tag
                                            closable
                                            @close="removeImg"
                                            type="primary" size="small"
                                    > {{files[0].name}} </el-tag>
                                    <span v-if="files[0].error" style="color: #FA5555">上传失败</span>
                                    <span v-else-if="files[0].success" style="color: #67C23A">成功</span>
                                    <span v-else-if="files[0].active" style="color: #409EFF">上传中</span>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-upload" v-if="files.length > 0 && !files[0].error"
                               :disabled="(!$refs.upload || !$refs.upload.active ? false : true)"
                               @click.prevent="$refs.upload.active = true">
                        上传文件
                    </el-button>
                    <el-button type="primary" v-if="files.length > 0 && files[0].error"
                               @click.prevent="$refs.upload.update(files[0],{active: true, error: '', progress: '0.00'})"
                    >重新上传</el-button>

                    <el-button v-if="dialogStatus == 'update'" type="primary" @click="update">编 辑</el-button>


                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
    </div>
</template>

<script>
    import { created, updated, deleted, deletedBatch, selectOne, selectList, UploadUrl } from '@/api/weixin/newsImg'
    import FileUpload from 'vue-upload-component'


    const sortOptions = [{label: '升序', key: 'ctime asc'}, {label: '降序', key: 'ctime desc'}]

    export default {
        name: 'NewsImg',
        components: {FileUpload},
        data() {
            return {
                list: [],
                total: null,
                listLoading: false,
                multipleSelection: [],
                listQuery: {
                    page: 1,
                    rows: 10,
                    title: undefined,
                    orderBy: 'ctime desc'
                },
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '编辑',
                    create: '创建'
                },
                sortOptions,
                form: {
                    url: null,
                    remarks: null
                },
                rules: {},
                files: [],
                uploadAuto: false,
                uploadAction: UploadUrl,
                autoCompress: 1024 * 1024 * 10,
                size: 1024 * 1024 * 10,
                thread: 3,
                accept: 'image/png,image/gif,image/jpeg,image/webp',
                extensions: 'gif,jpg,jpeg,png,webp',
                headers: {
                    'X-Token': 'xxxx'
                }
            }
        },
        created() {
            this.getTableData()
        },
        methods: {
            handleFilter() {//条件过滤
                this.listQuery.page = 1
                this.getTableData()
            },
            handleResetFilter() {//重置过滤条件
                this.$refs.filterForm.resetFields()
                this.getTableData()
            },
            handleDialogClose() {//关闭窗口回调函数
                this.resetForm()
            },
            handleSelectionChange(val) {//多选
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                this.listQuery.rows = val
                this.getTableData()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getTableData()
            },
            handleCreate() {//添加数据窗口
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
            },
            handleUpdate(row) {//修改数据窗口
                selectOne(row.id).then(response => {
                    this.dialogStatus = 'update'
                    this.dialogFormVisible = true
                    this.form = Object.assign({}, response.data)
                })
            },
            handleDelete(row) {//删除数据
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleted(row.id).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.getTableData()
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'warning', message: '已取消删除' })
                })
            },
            handleBatchDelete() {//批量删除数据
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if(this.multipleSelection.length > 0) {
                        let ids = []
                        for(let item of this.multipleSelection) {
                            ids.push(item.id)
                        }
                        deletedBatch({ids: ids.join(',')}).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getTableData()
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        })

                    } else {
                        this.$notify({
                            title: '提示', message: '请选择需要删除的记录',
                            type: 'warning', duration: 2000
                        })
                    }
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },

            update() {//修改数据
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        updated(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getTableData()
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                        })
                    }
                })
            },
            getTableData() {
                this.listLoading = true
                selectList(this.listQuery).then(response => {
                    this.list = response.data.data.list
                    this.total = response.data.data.total
                    this.listLoading = false
                }).catch(error => {
                    console.log(error)
                    this.listLoading = false
                })
            },
            resetForm() {//重置表单
                this.$refs['form'].resetFields()
                this.form = {
                    url: null,
                    remarks: null
                }
                this.files = []
            },
            removeImg() {
                this.files = []
                this.form = {
                    url: null,
                    remarks: null
                }
            },
            inputFilter(newFile, oldFile, prevent) {
                if (newFile && !oldFile) {
                    // 添加文件前
                    // 过滤系统文件 和隐藏文件
                    if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
                        return prevent()
                    }
                    // 过滤 php html js 文件
                    if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
                        return prevent()
                    }

                    // 自动压缩
                    if (newFile.file && newFile.type.substr(0, 6) === 'image/' && this.autoCompress > 0 && this.autoCompress < newFile.size) {
                        newFile.error = 'compressing'
                        const imageCompressor = new ImageCompressor(null, {
                            convertSize: Infinity,
                            maxWidth: 512,
                            maxHeight: 512,
                        })
                        imageCompressor.compress(newFile.file)
                            .then((file) => {
                                this.$refs.upload.update(newFile, { error: '', file, size: file.size, type: file.type })
                            })
                            .catch((err) => {
                                this.$refs.upload.update(newFile, { error: err.message || 'compress' })
                            })
                    }

                    if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
                        // 创建 blob 字段
                        newFile.blob = ''
                        let URL = window.URL || window.webkitURL
                        if (URL && URL.createObjectURL) {
                            newFile.blob = URL.createObjectURL(newFile.file)
                        }
                        // 缩略图
                        newFile.thumb = ''
                        if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
                            newFile.thumb = newFile.blob
                        }
                    }
                }
            },
            inputFile(newFile, oldFile) {
                if (newFile && !oldFile) {
                    // 添加文件
                }

                if (newFile && oldFile) {
                    // 更新文件

                    // 开始上传
                    if (newFile.active && !oldFile.active) {
                        // beforeSend
                        //设置每个文件携带的参数
                        newFile.data = Object.assign({}, this.form)

                        // 限定最小字节
                        if (newFile.size >= 0 && this.minSize > 0 && newFile.size < this.minSize) {
                            this.$refs.upload.update(newFile, { error: 'size' })
                        }
                    }
                    // 上传进度
                    if (newFile.progress !== oldFile.progress) {
                        //console.log('progress', newFile.progress, newFile)
                    }
                    // 上传错误
                    if (newFile.error !== oldFile.error) {
                        //console.log('error', newFile.error, newFile)
                    }
                    // 上传成功
                    if (newFile.success !== oldFile.success) {
                        //console.log('success', newFile.success, newFile)
                        this.dialogFormVisible = false
                        this.getTableData()
                    }
                }

                if (!newFile && oldFile) {
                    // 删除文件
                    // 自动删除 服务器上的文件
                    if (oldFile.success && oldFile.response.id) {
                        // $.ajax({
                        //   type: 'DELETE',
                        //   url: '/file/delete?id=' + oldFile.response.id,
                        // });
                    }
                }

                // 自动上传
                if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
                    if (this.uploadAuto && !this.$refs.upload.active) {
                        this.$refs.upload.active = true
                    }
                }
            }
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>

</style>
